package com.taikang.hmp.frame.common.chat;

import java.io.IOException;
import java.nio.CharBuffer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.sql.DataSource;

import net.sf.json.JSONObject;

import org.apache.commons.collections.map.LinkedMap;
import org.apache.commons.dbcp.BasicDataSource;

import com.taikang.framework.common.util.IDHelper;
import com.taikang.hmp.frame.common.HDConstant;

public class WebSocketMessageInboundPool {

	private static final Map<String, WebSocketMessageInbound> connections = new HashMap<String, WebSocketMessageInbound>();// 保存连接的Map容器
	public static Map<String, String> chatuser = new HashMap<String, String>();// 保存连接的用户
	public static Map<String, Set<Object>> healthuser = new HashMap<String, Set<Object>>();// 保存连接的用户
	public static String jdbcClassName = "oracle.jdbc.driver.OracleDriver";
	public static String url = "jdbc:oracle:thin:@139.129.29.11:1522:orcl";
	public static String userName = "hdhealth";
	public static String password = "123456";
	public static int i = 0;

	/**
	 * 向连接池中添加连接
	 * 
	 * @author zhaocs
	 */
	public static void addMessageInbound(WebSocketMessageInbound inbound) {
		System.out.println("user : " + inbound.getUser() + " 上线。");
		try {
			// chatuser = new HashMap<String,String>();
			if (chatuser == null || chatuser.isEmpty()) {
				loadUser();
			}
			if (HDConstant.CHAT_TYPE_HEALTHER.equals(inbound.getType())) {
				healthuser.put(inbound.getUser(), getHealtherUserList(inbound
						.getUser()));
			}
			// Iterator<String> it =chatuser.keySet().iterator();

			// while(it.hasNext()){
			// i++;
			// String keytemp = it.next();
			//			
			// System.out.println("key:"+keytemp);
			// System.out.println("name:"+i+chatuser.get(keytemp));
			// }

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		connections.put(inbound.getUser(), inbound);
	}

	public static void loadUser() {
		chatuser = new HashMap<String, String>();
		try {
			getAllUser("select b.user_id,a.name from hd_bs_customer a,hd_bs_auth_user b where b.custom_id=a.customer_id and (b.user_type<>'2' or b.user_type is null) ");
			getAllUser("select b.user_id,a.name from hd_bs_assistant a,hd_bs_auth_user b where b.custom_id=a.customer_id and b.user_type='2' ");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 获取所有的在线用户
	 * 
	 * @author zhaocs
	 */
	public static Set<Object> getOnlineUser() {
		HashMap result = new HashMap();
		Iterator temp = connections.keySet().iterator();
		while (temp.hasNext()) {
			ChatUser obj = new ChatUser();
			String id = (String) temp.next();
			obj.setId(id);
			obj.setName(chatuser.get(id));
			result.put(id, obj);
		}
		return result.entrySet();
	}

	/**
	 * 获取历史信息
	 * 
	 * @author zhaocs
	 */
	public static Set<Object> getHistoryMsg(String userid, String startdate,
			String state) {

		List mlist = getMsgDb(userid, startdate, state);
		LinkedMap result = new LinkedMap();
		for (int i = 0; i < mlist.size(); i++) {
			Map temp = (LinkedMap) mlist.get(i);
			JSONObject obj = JSONObject
					.fromObject("{\"from\":\"app\",\"to\":\"app\",\"content\":\"test\",\"timestamp\":\"2015-12-25 15:07:29\",\"type\":\"message\"}");
			obj.element("from", chatuser.get(temp.get("SEND_USER")));
			obj.element("to", chatuser.get(temp.get("RECEIVE_USER")));
			obj.element("fromid", temp.get("SEND_USER"));
			obj.element("toid", temp.get("RECEIVE_USER"));
			obj.element("content", temp.get("MESSAGE"));
			obj.element("timestamp", temp.get("SEND_TIME"));
			obj.element("state", temp.get("STATE"));
			// obj.element("to", temp.get("RECEIVE_USER"));
			result.put(temp.get("MSG_ID"), obj);
		}

		// result.put(2,
		// JSONObject.fromObject("{\"from\":\"appqrp\",\"to\":\"abc\",\"content\":\"测试qrp2\",\"timestamp\":1450950420857,\"type\":\"message\"}"));
		// result.put(3,
		// JSONObject.fromObject("{\"from\":\"abc\",\"to\":\"appqrp\",\"content\":\"测试qrp3\",\"timestamp\":1450950420897,\"type\":\"message\"}"));
		// result.put(4,
		// JSONObject.fromObject("{\"from\":\"abc\",\"to\":\"appzhao\",\"content\":\"测试zhao1\",\"timestamp\":1450950420897,\"type\":\"message\"}"));
		// result.put(5,
		// JSONObject.fromObject("{\"from\":\"appzhao\",\"to\":\"abc\",\"content\":\"测试zhao2\",\"timestamp\":1450950420897,\"type\":\"message\"}"));
		return result.entrySet();
	}

	/**
	 * 获取健康管理师信息
	 * 
	 * @author zhaocs
	 */
	public static Set<Object> getHealther(String userid) {

		List mlist = getHealtherMsg(userid);
		LinkedMap result = new LinkedMap();
		for (int i = 0; i < mlist.size(); i++) {
			Map temp = (LinkedMap) mlist.get(i);
			JSONObject obj = JSONObject
					.fromObject("{\"from\":\"app\",\"to\":\"app\",\"content\":\"test\",\"timestamp\":\"2015-12-25 15:07:29\",\"type\":\"message\"}");
			obj.element("from", chatuser.get(temp.get("SEND_USER")));
			obj.element("to", chatuser.get(temp.get("RECEIVE_USER")));
			obj.element("fromid", temp.get("SEND_USER"));
			obj.element("toid", temp.get("RECEIVE_USER"));
			obj.element("content", temp.get("MESSAGE"));
			obj.element("timestamp", temp.get("SEND_TIME"));
			// obj.element("to", temp.get("RECEIVE_USER"));
			result.put(temp.get("MSG_ID"), obj);
		}

		// result.put(2,
		// JSONObject.fromObject("{\"from\":\"appqrp\",\"to\":\"abc\",\"content\":\"测试qrp2\",\"timestamp\":1450950420857,\"type\":\"message\"}"));
		// result.put(3,
		// JSONObject.fromObject("{\"from\":\"abc\",\"to\":\"appqrp\",\"content\":\"测试qrp3\",\"timestamp\":1450950420897,\"type\":\"message\"}"));
		// result.put(4,
		// JSONObject.fromObject("{\"from\":\"abc\",\"to\":\"appzhao\",\"content\":\"测试zhao1\",\"timestamp\":1450950420897,\"type\":\"message\"}"));
		// result.put(5,
		// JSONObject.fromObject("{\"from\":\"appzhao\",\"to\":\"abc\",\"content\":\"测试zhao2\",\"timestamp\":1450950420897,\"type\":\"message\"}"));
		return result.entrySet();
	}

	/**
	 * 移除连接
	 * 
	 * @author zhaocs
	 */
	public static void removeMessageInbound(WebSocketMessageInbound inbound) {
		System.out.println("user : " + inbound.getUser() + " 下线。");
		connections.remove(inbound.getUser());
		// chatuser.remove(inbound.getUser());
	}

	/**
	 * 向特定的用户发送数据
	 * 
	 * @author zhaocs
	 */
	public static void sendMessageToUser(String user, String message) {
		try {
			System.out.println("send message to user : " + user
					+ " ,message content : " + message);
			WebSocketMessageInbound inbound = connections.get(user);
			if (inbound != null) {
				inbound.getWsOutbound().writeTextMessage(
						CharBuffer.wrap(message));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 向所有的用户发送消息
	 * 
	 * @author zhaocs
	 */
	public static void sendMessageToAllUser(String message) {
		try {
			Set<String> keySet = connections.keySet();
			for (String key : keySet) {
				WebSocketMessageInbound inbound = connections.get(key);
				if (inbound != null) {
					System.out.println("send message to user : " + key
							+ " ,message content : " + message);
					inbound.getWsOutbound().writeTextMessage(
							CharBuffer.wrap(message));
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void saveMsg(JSONObject obj) {

		String sql = "insert into hd_bc_dc_msg_record (msg_id,message,send_user,receive_user,send_time,state,source_cd,operater,operate_date)";
		sql = sql + " values(?,?,?,?,?,?,?,?,sysdate)";
		DBConnectionService dBConnectionService = new DBCPConnectionServiceImpl();
		Connection conn = dBConnectionService.getConnection(jdbcClassName, url,
				userName, password);
		ResultSet rs = null;
		try {

			PreparedStatement preparedStatement = conn.prepareStatement(sql);

			preparedStatement.setString(1, IDHelper.genUUID());
			preparedStatement.setString(2, obj.getString("content"));
			preparedStatement.setString(3, obj.getString("fromid"));
			preparedStatement.setString(4, obj.getString("toid"));
			preparedStatement.setString(5, obj.getString("timestamp"));
			preparedStatement.setString(6, "0");
			preparedStatement.setString(7, "diabetes");
			preparedStatement.setString(8, "system");
			preparedStatement.executeUpdate();
			conn.commit();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static List getMsgDb(String userid, String bdate, String state) {

		String sql = "select * from hd_bc_dc_msg_record where  (send_user=? or receive_user=?) and send_time>?  order by send_time";
		if (HDConstant.CHAT_STATE_UNREAD.equals(state)) {
			sql = "select * from hd_bc_dc_msg_record where  receive_user=?  and state='"
					+ state + "'  order by send_time";
		}
		List<Map> dataLists = new ArrayList<Map>();
		DBConnectionService dBConnectionService = new DBCPConnectionServiceImpl();
		Connection conn = dBConnectionService.getConnection(jdbcClassName, url,
				userName, password);
		ResultSet rs = null;
		try {

			PreparedStatement preparedStatement = conn.prepareStatement(sql);
			if (HDConstant.CHAT_STATE_UNREAD.equals(state)) {
				preparedStatement.setString(1, userid);
			} else {
				preparedStatement.setString(1, userid);
				preparedStatement.setString(2, userid);
				preparedStatement.setString(3, bdate);
			}
			rs = preparedStatement.executeQuery();

			while (rs.next()) {
				LinkedMap temp = new LinkedMap();
				temp.put("MSG_ID", rs.getString("MSG_ID"));
				temp.put("MESSAGE", rs.getString("MESSAGE"));
				temp.put("SEND_USER", rs.getString("SEND_USER"));
				temp.put("RECEIVE_USER", rs.getString("RECEIVE_USER"));
				temp.put("SEND_TIME", rs.getString("SEND_TIME"));
				temp.put("STATE", rs.getString("STATE"));
				dataLists.add(temp);
			}
			sql = "update hd_bc_dc_msg_record set state='1' where  receive_user=? and send_time>? and state='0' ";
			preparedStatement = conn.prepareStatement(sql);
			preparedStatement.setString(1, userid);
			preparedStatement.setString(2, bdate);
			preparedStatement.executeUpdate();
			conn.commit();

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return dataLists;
	}

	public static List getHealtherMsg(String userid) {

		String sql = "select * from(select * from hd_bc_dc_msg_record t where  receive_user=? order by send_time ) where rownum=1";
		List<Map> dataLists = new ArrayList<Map>();
		DBConnectionService dBConnectionService = new DBCPConnectionServiceImpl();
		Connection conn = dBConnectionService.getConnection(jdbcClassName, url,
				userName, password);
		ResultSet rs = null;
		try {

			PreparedStatement preparedStatement = conn.prepareStatement(sql);

			preparedStatement.setString(1, userid);

			rs = preparedStatement.executeQuery();

			while (rs.next()) {
				LinkedMap temp = new LinkedMap();
				temp.put("MSG_ID", rs.getString("MSG_ID"));
				temp.put("MESSAGE", rs.getString("MESSAGE"));
				temp.put("SEND_USER", rs.getString("SEND_USER"));
				temp.put("RECEIVE_USER", rs.getString("RECEIVE_USER"));
				temp.put("SEND_TIME", rs.getString("SEND_TIME"));
				dataLists.add(temp);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return dataLists;
	}

	public static Set getHealtherUserList(String userid) {

		String sql = "select * from hd_bz_di_relation where friend_id = ?";
		LinkedMap result = new LinkedMap();
		DBConnectionService dBConnectionService = new DBCPConnectionServiceImpl();
		Connection conn = dBConnectionService.getConnection(jdbcClassName, url,
				userName, password);
		ResultSet rs = null;
		try {

			PreparedStatement preparedStatement = conn.prepareStatement(sql);

			preparedStatement.setString(1, userid);

			rs = preparedStatement.executeQuery();

			while (rs.next()) {
				ChatUser obj = new ChatUser();
				String id = rs.getString("USER_ID");
				obj.setId(id);
				obj.setName(chatuser.get(id));
				if (connections.containsKey(id)) {
					obj.setOnline("1");
				}

				result.put(id, obj);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result.entrySet();
	}

	public static String getUserName(String userid, String type)
			throws SQLException {

		String sql = "";
		if (HDConstant.CHAT_TYPE_USER.equals(type)) {
			sql = "select a.name from hd_bs_customer a,hd_bs_auth_user b where b.custom_id=a.customer_id and b.user_type<>'2' and b.user_id='"
					+ userid + "' ";
		} else if (HDConstant.CHAT_TYPE_HEALTHER.equals(type)) {
			sql = "select a.name from hd_bs_assistant a,hd_bs_auth_user b where b.custom_id=a.customer_id and b.user_type='2' and b.user_id='"
					+ userid + "' ";
		}
		String result = "";
		List<Map> dataLists = new ArrayList<Map>();
		DBConnectionService dBConnectionService = new DBCPConnectionServiceImpl();
		ResultSet rs = null;
		Connection conn = dBConnectionService.getConnection(jdbcClassName, url,
				userName, password);
		try {

			PreparedStatement preparedStatement = conn.prepareStatement(sql);

			rs = preparedStatement.executeQuery();

			while (rs.next()) {
				result = rs.getString("name");

			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (rs != null) {
				rs.close();
			}
			conn.close();
		}
		return result;
	}

	public static void getAllUser(String sql) throws SQLException {

		String result = "";
		List<Map> dataLists = new ArrayList<Map>();
		DBConnectionService dBConnectionService = new DBCPConnectionServiceImpl();
		ResultSet rs = null;
		Connection conn = dBConnectionService.getConnection(jdbcClassName, url,
				userName, password);
		try {

			PreparedStatement preparedStatement = conn.prepareStatement(sql);

			rs = preparedStatement.executeQuery();

			while (rs.next()) {
				// result = rs.getString("name");
				i++;
				chatuser.put(rs.getString("user_id"), rs.getString("name"));
				// System.out.println("key:"+rs.getString("user_id"));
				// System.out.println("name:"+i+":"+rs.getString("name"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (rs != null) {
				rs.close();
			}
			conn.close();
		}
	}

	/**
	 * 根据配置信息取得数据库连接
	 * 
	 * @param driverClassName
	 * @param url
	 * @param userName
	 * @param password
	 * @return
	 */

	public static Connection getConnection(String driverClassName, String url,
			String userName, String password) {
		DataSource ds = getDataSource(driverClassName, url, userName, password);
		Connection conn = null;
		try {
			conn = ds.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 取得数据源
	 * 
	 * @param driverClassName
	 * @param url
	 * @param userName
	 * @param password
	 * @return
	 */
	private static DataSource getDataSource(String driverClassName, String url,
			String userName, String password) {
		BasicDataSource ds = new BasicDataSource();
		ds.setDriverClassName(driverClassName);
		ds.setUsername(userName);
		ds.setPassword(password);
		ds.setUrl(url);
		return ds;
	}

}